package com.crack.nga2.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.crack.nga2.R;
import com.crack.nga2.span.ClickableMovementMethod;
import com.crack.nga2.utils.GlobalConst;
import com.crack.nga2.volley.LoginRequest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LoginActivity extends AppCompatActivity {
    private EditText editName, editPassword;
    private boolean loading = false;
    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mQueue = NgaApplication.getQueue();
        Log.i("tag","mQueue---->"+mQueue);
        editName = (EditText) findViewById(R.id.edit_name);
        editPassword = (EditText) findViewById(R.id.edit_password);
        TextView forget = (TextView) findViewById(R.id.tv_forget);
        SpannableString string = new SpannableString(forget.getText().toString());
        string.setSpan(new UnderlineSpan(), 0, string.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        forget.setText(string);
        forget.setMovementMethod(ClickableMovementMethod.getInstance());
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.action_return:
                finish();
                break;
            case R.id.action_register:
                //注册
                break;
            case R.id.tv_forget:
                //忘记密码
                break;
            case R.id.btn_login:
                //登录
                if (!loading) {
                    login();
                }
                break;
        }
    }

    private void login() {
        if (TextUtils.isEmpty(editName.getText())) {
            editName.setError("不能为空");
            return;
        }
        if (TextUtils.isEmpty(editPassword.getText())) {
            editPassword.setError("不能为空");
            return;
        }
        loading = true;
        String name = editName.getText().toString();
        String password = editPassword.getText().toString();
        mQueue.add(new LoginRequest(name, password,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        GlobalConst.isLogin = true;
                        GlobalConst.Cookie = response;
                        //获取uid
                        Pattern p = Pattern.compile("(?<=ngaPassportUid=)(\\d+?)(?=;)");
                        Matcher m = p.matcher(response);
                        if (m.find()) {
                            GlobalConst.UID = Integer.parseInt(m.group());
                        }
                        //获取用户名
                        p = Pattern.compile("(?<=ngaPassportUrlencodedUname=)(.+?)(?=;)");
                        m = p.matcher(response);
                        if (m.find()) {
                            try {
                                GlobalConst.username = URLDecoder.decode(URLDecoder.decode(m.group(), "GBK"), "GBK");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        //写入缓存文件
                        File file = new File(getFilesDir(), "cookie.cache");
                        try {
                            if (file.exists() || file.createNewFile()) {
                                FileWriter writer = new FileWriter(file);
                                writer.write(response);
                                writer.flush();
                                writer.close();
                                Log.i("tag", file + ":");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(LoginActivity.this, "登录状态保存失败", Toast.LENGTH_SHORT).show();
                        }
                        loading = false;
                        setResult(1);
                        finish();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                        loading = false;
                    }
                }));
    }

}
